<template>
	<el-form ref="ruleFormRef" :model="state.ruleForm" size="large" :rules="rules" class="login-content-form">
		<el-form-item class="login-animation1" prop="username">
			<el-input type="text" placeholder="请输入用户帐号" @keydown.enter="onSignIn(ruleFormRef)"
				v-model="state.ruleForm.username" clearable autocomplete="off">
				<template #prefix>
					<el-icon class="el-input__icon"><ele-User /></el-icon>
				</template>
			</el-input>
		</el-form-item>
		<el-form-item class="login-animation2" prop="password">
			<el-input :type="state.isShowPassword ? 'text' : 'password'" @keydown.enter="onSignIn(ruleFormRef)"
				placeholder="请输入用户密码" v-model="state.ruleForm.password" autocomplete="off">
				<template #prefix>
					<el-icon class="el-input__icon"><ele-Unlock /></el-icon>
				</template>
				<template #suffix>
					<i class="iconfont el-input__icon login-content-password"
						:class="state.isShowPassword ? 'icon-yincangmima' : 'icon-xianshimima'"
						@click="state.isShowPassword = !state.isShowPassword">
					</i>
				</template>
			</el-input>
		</el-form-item>
		<el-form-item class="login-animation3">
			<el-col :span="15">
				<el-input type="text" maxlength="4" placeholder="请输入验证码" v-model="state.ruleForm.code" clearable
					@keydown.enter="onSignIn(ruleFormRef)" autocomplete="off">
					<template #prefix>
						<el-icon class="el-input__icon"><ele-Position /></el-icon>
					</template>
				</el-input>
			</el-col>
			<el-col :span="1"></el-col>
			<el-col :span="8" style="height:38px;">
				<div style="height: 38px; width: 120px; cursor: pointer" @click="createCode" v-loading="captchaLoading">
					<img style="width:100%;height:100%;" :src="state.captcha" />
				</div>
			</el-col>
		</el-form-item>
		<el-form-item class="login-animation4">
			<el-button type="primary" class="login-content-submit" @click="onSignIn(ruleFormRef)"
				:loading="state.loading.signIn">
				<span>登 录</span>
			</el-button>
		</el-form-item>
	</el-form>

	<UpdatePassword ref='updatePasswordRef' @update-success="handleUpdateSuccess" />
</template>

<script lang="ts" setup name="account">
import { toRefs, reactive, defineComponent, computed, ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { storeToRefs } from 'pinia';
import { useThemeConfig } from '/@/stores/themeConfig';
import { initFrontEndControlRoutes } from '/@/router/frontEnd';
import { initBackEndControlRoutes } from '/@/router/backEnd';
import { Local, Session } from '/@/utils/storage';
import { formatAxis } from '/@/utils/formatTime';
import { NextLoading } from '/@/utils/loading';
import watermark from '/@/utils/watermark';
import { useLoginApi } from '/@/api/login/index';

import UpdatePassword from '/@/views/personal/components/FormDialog.vue'

const loginApi = useLoginApi()
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const route = useRoute();
const router = useRouter();
const state = reactive({
	isShowPassword: false,
	ruleForm: {
		username: 'longzb',
		password: 'longzb@123',
		code: '',
	},
	loading: {
		signIn: false,
	},
	randomStr: '',
	captcha: '',
	userInfo: {},
	accessToken: ''
});

const captchaLoading = ref(false);

const updatePasswordRef = ref();

const ruleFormRef = ref<FormInstance>();

//验证规则
const rules = reactive<FormRules>({
	username: [
		{ required: true, message: '请输入用户帐号', trigger: 'blur' },
		{ min: 3, max: 12, message: '用户帐号长度为3-12位', trigger: 'blur' },
	],
	password: [
		{ required: true, message: '请输入用户密码', trigger: 'blur' },
	],
})

onMounted(() => {
	createCode();//创建验证码
})

const createCode = async () => {
	var randomStr = randomString(8)
	state.randomStr = randomStr
	captchaLoading.value = true;
	const data = await loginApi.code({ randomStr });
	captchaLoading.value = false;
	if (data) {
		state.captcha = 'data:image/jpeg;base64,' + arrayBufferToBase64(data)
	} else {
		ElMessage.error('请求验证码错误');
	}
}

const arrayBufferToBase64 = (buffer: any) => {
	var binary = ''
	var bytes = new Uint8Array(buffer)
	var len = bytes.byteLength
	for (var i = 0; i < len; i++) {
		binary += String.fromCharCode(bytes[i])
	}
	return window.btoa(binary)
}

const randomString = (e: any) => {
	e = e || 32
	let t = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678', a = t.length, n = ''
	for (let i = 0; i < e; i++) {
		n += t.charAt(Math.floor(Math.random() * a))
	}
	return n
}

//密码修改成功
const handleUpdateSuccess = () => {
	loginCallback();
}


// 时间获取
const currentTime = computed(() => {
	return formatAxis(new Date());
});

const loginCallback = async () => {
	//是否开启后端控制路由
	if (!themeConfig.value.isRequestRoutes) {
		// 前端控制路由，2、请注意执行顺序
		await initFrontEndControlRoutes();
		signInSuccess();
	} else {
		// 模拟后端控制路由，isRequestRoutes 为 true，则开启后端控制路由
		// 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
		await initBackEndControlRoutes();
		// 执行完 initBackEndControlRoutes，再执行 signInSuccess
		signInSuccess();
	}
}
// 登录
const onSignIn = async (formEl: FormInstance | undefined) => {
	if (!formEl) return
	await formEl.validate((valid, fields) => {
		if (valid) {
			state.loading.signIn = true;
			loginApi.signIn({ ...state.ruleForm, uuid: state.randomStr, grantType: 'password' }).then(async res => {
				if (res) {
					const { tokenInfo, userInfo, defaultPassword, loginTime } = res.data
					// 存储 token 到浏览器缓存
					Session.set(tokenInfo.tokenName, tokenInfo.tokenValue);
					if (themeConfig.value.isWartermark) {
						Session.set('wartermarkText', userInfo.name + ' ' + loginTime)
						watermark.set(Session.get('wartermarkText'))
					}
					if (defaultPassword) {
						//需要修改密码
						updatePasswordRef.value.acceptParams();
					} else {
						loginCallback();
					}

				}
				state.loading.signIn = false;
			})
		} else {
			console.log('error submit!', fields)
		}
	})
};
// 登录成功后的跳转
const signInSuccess = () => {
	// 初始化登录成功时间问候语
	let currentTimeInfo = currentTime.value;
	// 登录成功，跳到转首页
	// 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
	if (route.query?.redirect) {
		router.push({
			path: <string>route.query?.redirect,
			query: Object.keys(<string>route.query?.params).length > 0 ? JSON.parse(<string>route.query?.params) : '',
		});
	} else {
		router.push('/');
		// window.location.href = '/#/home'
	}
	// 登录成功提示
	// 关闭 loading
	state.loading.signIn = true;
	const signInText = '欢迎回来！';
	ElMessage.success(`${currentTimeInfo}，${signInText}`);
	NextLoading.start();
};
</script>

<style scoped lang="scss">
.login-content-form {
	margin-top: 20px;

	@for $i from 1 through 4 {
		.login-animation#{$i} {
			opacity: 0;
			animation-name: error-num;
			animation-duration: 0.5s;
			animation-fill-mode: forwards;
			animation-delay: calc($i/10) + s;
		}
	}

	.login-content-password {
		display: inline-block;
		width: 20px;
		cursor: pointer;

		&:hover {
			color: #909399;
		}
	}

	.login-content-code {
		width: 100%;
		padding: 0;
		font-weight: bold;
		letter-spacing: 5px;
	}

	.login-content-submit {
		width: 100%;
		letter-spacing: 2px;
		font-weight: 300;
		margin-top: 15px;
	}
}
</style>
